package com.hmall.gateway.Filter;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher =new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1，获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.判断请求是否需要认证
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        List<String> headers = request.getHeaders().get("authorization");
        String token =null;
        if (headers != null && !headers.isEmpty()){
            token=headers.get(0);
        }
        Long  studentId = null;
        //3.解析
        try {
          studentId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //传递用户信息
        Long finalStudentId = studentId;
        ServerWebExchange swe = exchange.mutate().request(builder -> builder.header("user-info", finalStudentId.toString())).build();
        //4.放行
        return chain.filter(swe);
    }
    //pan'duan'lu'jia
    private boolean isExclude(String path) {
        for (String pattern : authProperties.getExcludePaths()){
            if(antPathMatcher.match(pattern,path)){
                return true;
            }
        }
        return false;//不需要拦截
    }

    @Override
    public int getOrder() {
        return 0;
    }
}





